import { useAppConfig } from '@vben/hooks';
import { preferences } from '@vben/preferences';
import {
  authenticateResponseInterceptor,
  errorMessageResponseInterceptor,
  RequestClient,
} from '@vben/request';
import { useAccessStore } from '@vben/stores';

import { message } from 'ant-design-vue';

import { useAuthStore } from '#/store';

import { refreshTokenApi } from './core';

const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);

function createRequestClient(baseURL: string) {
  const client = new RequestClient({
    baseURL,
  });

  /**
   * 从 localStorage 获取 `accessToken`
   */
  function getAccessTokenFromLocalStorage(): null | string {
    const rawData = localStorage.getItem('vben-web-antd-5.4.8-dev-core-access');
    try {
      const parsedData = rawData ? JSON.parse(rawData) : null;
      return parsedData?.accessToken || null; // 返回 accessToken
    } catch (error) {
      console.error('无法从本地存储解析accessToken:', error);
      return null;
    }
  }

  /**
   * 重新认证逻辑
   */
  async function doReAuthenticate() {
    console.warn('访问令牌或刷新令牌无效或已过期。');
    const accessStore = useAccessStore();
    const authStore = useAuthStore();
    accessStore.setAccessToken(null);
    if (
      preferences.app.loginExpiredMode === 'modal' &&
      accessStore.isAccessChecked
    ) {
      accessStore.setLoginExpired(true);
    } else {
      await authStore.logout();
    }
  }

  /**
   * 刷新token逻辑
   */
  async function doRefreshToken() {
    const accessStore = useAccessStore();
    const resp = await refreshTokenApi();
    const newToken = resp.data;
    accessStore.setAccessToken(newToken);
    return newToken;
  }

  function formatToken(token: null | string) {
    return token ? `Bearer ${token}` : null;
  }

  // 请求头处理
  client.addRequestInterceptor({
    fulfilled: async (config) => {
      // 从 localStorage 获取 token
      const token = getAccessTokenFromLocalStorage();

      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      } else {
        console.warn('请求时未找到有效的 token');
      }

      return config;
    },
  });

  // 修改响应数据解构逻辑
  client.addResponseInterceptor({
    fulfilled: (response) => {
      const { data, status } = response;
      if (status >= 200 && status < 300) {
        return data;
      }
      throw new Error(`HTTP 状态码异常: ${status}`);
    },
    rejected: (error) => {
      const status = error?.response?.status;
      if (status === 403) {
        console.error('无权限访问此接口', error.message);
      } else if (status === 401) {
        console.warn('登录过期，请重新登录');
        doReAuthenticate();
      }
      return Promise.reject(error);
    },
  });

  // token过期的处理
  client.addResponseInterceptor(
    authenticateResponseInterceptor({
      client,
      doReAuthenticate,
      doRefreshToken,
      enableRefreshToken: preferences.app.enableRefreshToken,
      formatToken,
    }),
  );

  // 通用的错误处理
  client.addResponseInterceptor(
    errorMessageResponseInterceptor((msg: string, error) => {
      const responseData = error?.response?.data ?? {};
      const errorMessage = responseData?.error ?? responseData?.message ?? '';
      message.error(errorMessage || msg);
    }),
  );

  return client;
}

export const requestClient = createRequestClient(apiURL);

export const baseRequestClient = new RequestClient({ baseURL: apiURL });
